package design.donkey.auto.ddl.analysis;

import java.util.Collections;
import java.util.List;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import design.donkey.auto.ddl.model.ColumnMetaModel;
import design.donkey.framework.common.orm.annotation.PrimaryKeyType;
import lombok.extern.slf4j.Slf4j;

/**
 * myBatis plus 注解支持
 *
 * @author zhangjiakung
 * @since 0.0.1
 */
@Slf4j
public class MyBatisPlusAnnotationAnalysis extends AnnotationAnalysis {

    @Override
    public boolean isDomain(Class<?> domainClazz) {
        return super.isDomain(domainClazz) || domainClazz.getAnnotation(TableName.class) != null;
    }

    @Override
    protected String getTableSchema(Class<?> domainClazz) {
        TableName tableAnnotation = domainClazz.getAnnotation(TableName.class);
        return get(tableAnnotation == null ? null : tableAnnotation.schema())
            .orElseGet(() -> super.getTableSchema(domainClazz));
    }

    @Override
    protected String getTableName(Class<?> domainClazz) {
        TableName tableAnnotation = domainClazz.getAnnotation(TableName.class);
        return get(tableAnnotation == null ? null : tableAnnotation.value())
            .orElseGet(() -> super.getTableName(domainClazz));
    }

    @Override
    protected List<ColumnMetaModel> getColumns(ModelField field) {
        // 支持jpa Transient 注解
        TableField tableFieldAnnotation = field.getAnnotation(TableField.class);
        if (tableFieldAnnotation != null && !tableFieldAnnotation.exist()) {
            return Collections.emptyList();
        }
        return super.getColumns(field);
    }

    @Override
    protected String getColumnName(ModelField field) {
        TableField tableFieldAnnotation = field.getAnnotation(TableField.class);
        TableId idAnnotation = field.getAnnotation(TableId.class);
        return get(tableFieldAnnotation == null ? null : tableFieldAnnotation.value(),
            idAnnotation == null ? null : idAnnotation.value()).orElseGet(() -> super.getColumnName(field));
    }

    @Override
    protected boolean getColumnPrimaryKey(ModelField field) {
        // 用户自定义了 字段类型
        TableId idAnnotation = field.getAnnotation(TableId.class);
        if (idAnnotation != null) {
            return true;
        }
        return super.getColumnPrimaryKey(field);
    }

    @Override
    protected PrimaryKeyType getColumnPrimaryKeyType(ModelField field) {
        // 用户自定义了 字段类型
        TableId idAnnotation = field.getAnnotation(TableId.class);
        if (idAnnotation != null) {
            IdType type = idAnnotation.type();
            if (IdType.AUTO.equals(type)) {
                return PrimaryKeyType.JDBC;
            }
            return PrimaryKeyType.SOFT;
        }
        return super.getColumnPrimaryKeyType(field);
    }
}
